import 'dart:convert';
import 'dart:io';

const String request_page = "lib/common/network/request.dart";

void main() {
  // _test();
  // _start();
  // print(_capitalize(_res));
  _start();
}

void _testApply() async {
  final Map<String, Function> map = {"func": _sum, "add": _add};
  final res = await Function.apply(map['func']!, [0, 'a']);
  print(res);
  final res1 = await Function.apply(map['add']!, [0, 'a']);
  print(res1);
}

Future<String> _sum(int a, dynamic b) {
  return Future.value('$a$b');
}

Future<String> _add() {
  return Future.value('dd');
}

void _start() {
  //1. 解析json
  final String jsonStr = File('openapi.json').readAsStringSync();
  final Map jsonMap = json.decode(jsonStr);
  print(jsonMap['openapi']);
  final Map paths = jsonMap['paths'];
  String request = '';
  String requestMethod = '';
  String functionMap = '';
  //
  paths.forEach((key, value) {
    final _name = toCamelCase(key.split("/").last);
    functionMap += '"$_name":$_name, ';
    requestMethod += _getRequestMethod(key, value);
  });
  request = '''
import 'package:arc_web/utils/network.dart';

abstract class Request {
 static Map<String, Function> functionMap = {$functionMap};
}''';

  final File requestFile = File(request_page);
  if (!requestFile.existsSync()) {
    request = request.replaceFirst(RegExp(r"(?<=abstract class Request {)"), "\n$requestMethod");
  } else {
    // 方法追加到请求中
    String reqContent = requestFile.readAsStringSync();
    request = reqContent.replaceFirst(RegExp(r"(?<=abstract class Request {)"), "\n$requestMethod");
  }
  requestFile.writeAsStringSync(request);
  requestFile.createSync();
}

String _getRequestMethod(String key, Map sender) {
  final Map _get = sender['get'];
  final List parameters = _get['parameters'];
  String title = _get['summary'];
  String _line = '';
  String _param = '';
  String _reqParam = '';
  parameters.forEach((element) {
    _line += ' ${element["name"]}: ${element["description"]}';
    if (parameters.last == element) {
      _param += 'String ${element['name']}';
      _reqParam += '"${element["name"]}": ${element["name"]}';
    } else {
      _param += 'String ${element['name']}, ';
      _reqParam += '"${element["name"]}": ${element["name"]}, ';
    }
  });

  String res = '''
   // $title
   // $_line
   static Future<dynamic> ${toCamelCase(key.split("/").last)}($_param) {
    return NetworkTool.get("$key", params: {$_reqParam});
  }
''';
  return res;
}

String toCamelCase(String input) {
  List<String> words = input.split('_');
  String camelCase = words[0];

  for (int i = 1; i < words.length; i++) {
    String word = words[i];
    camelCase += word[0].toUpperCase() + word.substring(1);
  }

  return camelCase;
}
